package cn.tedu.charging.order.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * rabbit-mq配置类
 * 配置 连接信息，用户名，密码，端口号，虚拟机名，队列名，交换机名，路由key
 */
@Configuration
public class RabbitConfiguration {

    public static final String EXCHANGE_NAME = "charging_order_exchange";

    private static final String QUEUE_NAME = "charging_order_queue";

    public static final String ROUTING_KEY = "charging_order_routing_key";

    private static final String DEAD_LETTER_EXCHANGE_NAME = "charging_dead_letter_order_exchange";

    public static final String DEAD_LETTER_QUEUE_NAME = "charging_dead_order_queue";

    private static final String DEAD_LETTER_ROUTING_KEY = "charging_dead_order_routing_key";

    /**
     * 定义正常的订单的交换机（Exchange）
     * @return
     */
    @Bean
    public DirectExchange orderExchange() {
        //消息持久化,不能丢
        Boolean durable = true;
        return new DirectExchange(EXCHANGE_NAME,durable,false);
    }

    /**
     * 定义正常的订单的队列（Queue）
     * @return
     */
    @Bean
    public Queue orderQueue() {
        Map<String, Object> args = new HashMap<>();
        //设置消息的存活时间
        //模拟充电充满需要2分钟
        Integer ttl = 2 * 60 * 1000;
        args.put("x-message-ttl",ttl);
        //设置queue的死信exchange
        args.put("x-dead-letter-exchange",DEAD_LETTER_EXCHANGE_NAME);
        //设置queue的死信routingKey
        args.put("x-dead-letter-routing-key",DEAD_LETTER_ROUTING_KEY);
        //延迟队列，在消息很多的时候，把消息存储到磁盘中，减少内存的使用，提高性能
        args.put("x-queue-mode","lazy");
        //持久化,保证队列消息不会丢失
        Boolean durable = true;
        //参数1：队列名，参数2：是否持久化，参数3：是否独占队列，参数4：是否自动删除
        return new Queue(QUEUE_NAME,durable, true,false,args);
    }

    /**
     * 绑定正常的订单的队列（Queue）到正常的订单的交换机（Exchange）
     * @return
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue())
                .to(orderExchange()).with(ROUTING_KEY);
    }

    /**
     * 定义死信的交换机（Exchange）
     * @return
     */
    @Bean
    public DirectExchange deadLetterExchange() {
        //持久化,保证队列消息不会丢失
        Boolean durable = true;
        return new DirectExchange(DEAD_LETTER_EXCHANGE_NAME, durable, false);
    }

    /**
     * 定义死信的队列（Queue）
     * @return
     */
    @Bean
    public Queue deadLetterQueue() {
        //持久化,保证队列消息不会丢失
        Boolean durable = true;
        return new Queue(DEAD_LETTER_QUEUE_NAME,durable);
    }

    /**
     * 绑定死信的队列（Queue）到死信的交换机（Exchange）
     * @return
     */
    @Bean
    public Binding deadLetterOrderBinding() {
        return BindingBuilder.bind(deadLetterQueue())
                .to(deadLetterExchange()).with(DEAD_LETTER_ROUTING_KEY);
    }
}
